package com.baizhi.realm;
import com.baizhi.dao.AdminDao;
import com.baizhi.dao.ResourceDao;
import com.baizhi.dao.RoleDao;
import com.baizhi.entity.Admin;
import com.baizhi.entity.Resource;
import com.baizhi.entity.Role;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2019/4/19.
 */




public class MyRealm2 extends AuthorizingRealm {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private ResourceDao resourceDao;



    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        1.获取方法传入的身份信息 账号  当前用户的用户名
        String username = (String) principals.getPrimaryPrincipal();
//        2.通过用户名 连接数据库 获取当前用户相关的角色信息  和 权限信息

        List<Role> roles1 = roleDao.selectUserRole(username);
        Set<String> roles = new HashSet<>();

        for (Role role : roles1) {
            roles.add(role.getRoleName());
        }

        //查询指定角色集合拥有的所有权限
        Set<String> permissions = new HashSet<>();
        List<Resource> resources = resourceDao.selectResourceByUsername(username);
        for (Resource resource : resources) {
            permissions.add(resource.getResourcePermission());

        }

        //3.将信息放在info中
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //将角色信息加入info中
        info.setRoles(roles);
        //将权限信息加入info中
        info.setStringPermissions(permissions);

        return info;
    }

    /**
     * 实现认证信息获取的方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Admin admin = adminDao.selectByName(username);
        if (admin!=null){
            SimpleAccount simpleAccount = new SimpleAccount(admin.getAdminUsername(),admin.getAdminPassword(), ByteSource.Util.bytes(admin.getSalt()),this.getName());
            return simpleAccount;
        }
        return null;
    }
}